<script setup lang='ts'>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { useGetDictData } from '@fl/api/advertising-api'
import { goodsGroupDetail, useGoodsGroupDel, useGoodsGroupList, useGoodsGroupSave, useGoodsGroupSwitchStatus } from '@fl/api/advertising-api/goods-group'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import goodsConfig from './components/goods-config.vue'
import { adgDialogTag } from './type'

const route = useRoute();

const initialState = {
    activeStatus: undefined,
    name: '',
}
const state = ref(cloneDeep(initialState))
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

const dialogVisible = ref(false)
const dialogWidth = ref(666)
const dialogTitle = ref('')
const formRef = ref()
const form = ref()
const initState = {
    id: undefined,
    name: '',
    platform: [],
}

const groupId = ref() // 商品组id
const platformOptions = ref()

const list = ref([])
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))

onMounted(() => {
    if(route.query.id) {
        groupId.value = Number(route.query.id)
        dialogWidth.value = 1060
        dialogTitle.value = adgDialogTag.ADVERTISING_CONFIG
        dialogVisible.value = true
    }
})


const { data, isLoading, refetch } = useGoodsGroupList(params)
const { data: dictList } = useGetDictData({ dictType: 'platform' })
const { isPending, mutate: mutateUpdate } = useGoodsGroupSave()
const { mutate: mutateDel } = useGoodsGroupDel()
const { mutate: mutateSwitch } = useGoodsGroupSwitchStatus()

watchEffect(() => {
    if (data.value) {
        list.value = cloneDeep(data.value.rows).reduce((pre, cur) => {
            cur.activeStatus = cur.activeStatus === 1 ? 1 : 0
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = data.value.total!
    }
    if (dictList.value) {
        platformOptions.value = dictList.value.platform
        console.log('platformOptions.value', platformOptions.value)
    }
})

// watchEffect(() => {
//     if (dictList.value) {
//         platformOptions.value = dictList.value.platform
//         console.log('platformOptions.value', platformOptions.value)
//     }
// })

/**
 * methods start
 */

function submitSearch(values) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

// 新增商品
async function addAdertisingGroup() {
    dialogTitle.value = adgDialogTag.ADD_ADVERTISING_GROUP
    form.value = cloneDeep(initState)
    dialogVisible.value = true
    dialogWidth.value = 666
}

// 提交新增/编辑/复制商品组
function adGroupSubmit(values) {
    const platform = values.platform.join(',')
    const params = {
        ...values,
        platform,
    }
    switch (dialogTitle.value) {
        case '新增商品组':
        case '复制商品组':
            mutateUpdate(params, {
                onSuccess: () => {
                    ElMessage.success('新增成功')
                    dialogVisible.value = false
                },
            })
            break
        case '编辑商品组':
            mutateUpdate(params, {
                onSuccess: () => {
                    ElMessage.success(dialogTitle.value === adgDialogTag.EDIT_ADVERTISING_GROUP ? '编辑成功' : '复制成功')
                    dialogVisible.value = false
                },
            })
            break
    }
}

// 编辑/复制商品组
async function setAdgroup(row, title) {
    dialogTitle.value = title
    goodsGroupDetail({
        id: row.id,
    }).then((data) => {
        const { id, name, platform, remark } = data
        const newPlatform = (platform && platform.split(',')) || []
        form.value = {
            id,
            name,
            platform: newPlatform,
            remark,
        }
        if (title === adgDialogTag.COPY_ADVERTISING_GROUP) {
            form.value.name += '副本'
            form.value.copyId = id
            delete form.value.id
        }

        dialogVisible.value = true
    })
}

// 配置商品
function adConfig(row, title) {
    groupId.value = row.id
    dialogWidth.value = 1060
    dialogTitle.value = title
    dialogVisible.value = true
}

// 删除商品组
function delAdgroup(row) {
    const { id, name } = row
    ElMessageBox.confirm(
        `你确实要删除商品组『${name}』吗？`,
        '删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            mutateDel({
                id,
            }, {
                onSuccess: () => {
                    ElMessage.success('删除成功')
                },
            })
        }).catch(() => {
            ElMessage({
                message: '取消删除',
                type: 'info',
            })
        })
}

function closeDialog() {
    dialogVisible.value = false
    dialogTitle.value = ''
    refetch()
}

// 启用禁用
function switchActiveStatus(row) {
    const params = {
        enable: row.activeStatus,
        id: row.id,
    }
    mutateSwitch(params, {
        onError() {
            setTimeout(() => {
                row.activeStatus = row.activeStatus === 1 ? 0 : 1
            }, 500)
        },
        onSuccess: (res) => {
            console.log('res', res)
            const tips = row.activeStatus === 1 ? '已启用' : '已禁用'
            ElMessage({
                message: tips,
                type: row.activeStatus === 1 ? 'success' : 'info',
            })
        },
    })
}

/**
 * methods end
 */


const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '搜索关键词',
        prop: 'name',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '活动状态',
        options: [
            {
                label: '未开始',
                value: 'NO',
            },
            {
                label: '进行中',
                value: 'YES',
            },
        ],
        prop: 'activeStatus',
        valueType: 'select',
    },
]

const formRule = {
    name: [
        {
            message: '请输入商品组名称',
            required: true,
            trigger: 'blur',
        },
    ],
    platform: [
        {
            message: '请选择平台类型',
            required: true,
            trigger: 'blur',
        },
    ],
}

const formColumns = ref(cloneDeep(
    [
        {
            label: '商品组名称',
            labelWidth: 100,
            prop: 'name',
        },
        {
            fieldProps: {
                filterable: true,
                multiple: true,
            },
            label: '平台类型',
            labelWidth: 100,
            options: computed(() => {
                return platformOptions.value
            }),
            prop: 'platform',
            valueType: 'select',
        },
        {
            label: '备注',
            labelWidth: 100,
            prop: 'remark',
            valueType: 'textarea',
        },
    ]
))

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'name', title: '商品组名称' },
        { field: 'snapshotQuantity', title: '分期数量', width: 80 },
        { field: 'projectQuantity', title: '楼盘/产品数量', width: 80 },
        { field: 'platform', title: '平台类型' },
        { field: 'createTime', title: '创建时间' },
        { field: 'creator', title: '操作人' },
        { field: 'remark', title: '备注' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '启用/禁用', width: 100 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 210 },
    ],
})

</script>

<template>
    <div class="goods-group">
        <div class="goods-group-list">
            <ElCard class="mb-20" shadow="never">
                <SearchForm v-bind="state" :columns="columns" submit-text="搜索" @reset="resetSearch"
                    @submit="submitSearch" />
            </ElCard>

            <ElCard shadow="never">
                <SearchTable v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="list"
                    @page-change="handlePageChange">
                    <template #toolbar_buttons>
                        <el-button plain type="primary" @click="addAdertisingGroup">
                            新增商品组
                        </el-button>
                    </template>

                    <template #activeStatus="{ row }">
                        <el-switch v-model="row.activeStatus" :active-value="1" :inactive-value="0"
                            @change="switchActiveStatus(row)" />
                    </template>

                    <template #operate="{ row }">
                        <div class="operate-btns">
                            <el-button type="primary" text
                                @click="setAdgroup(row, adgDialogTag.EDIT_ADVERTISING_GROUP)">
                                编辑
                            </el-button>

                            <el-button type="primary" text @click="adConfig(row, adgDialogTag.ADVERTISING_CONFIG)">
                                配置商品
                            </el-button>

                            <el-button type="info" text @click="setAdgroup(row, adgDialogTag.COPY_ADVERTISING_GROUP)">
                                复制
                            </el-button>

                            <el-button type="info" text @click="delAdgroup(row)">
                                删除
                            </el-button>
                        </div>
                    </template>
                </SearchTable>
            </ElCard>
        </div>

        <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false"
            :title="dialogTitle" :width="dialogWidth"
            :class="[adgDialogTag.SELECT_MATERIAL, adgDialogTag.ADVERTISING_CONFIG].includes(dialogTitle) ? 'ad-config-dialog' : ''"
            @closed="closeDialog">
            <template #header>
                <h3 class="dialog-title">
                    {{ dialogTitle }}
                    <span v-if="dialogTitle === adgDialogTag.ADVERTISING_CONFIG"
                        class="mark">（更改商品组数据后，所有引用该商品组的页面均会自动更新为最新版数据）</span>
                </h3>
            </template>
            <!-- 新增/编辑/复制商品组 -->
            <template
                v-if="[adgDialogTag.ADD_ADVERTISING_GROUP, adgDialogTag.EDIT_ADVERTISING_GROUP, adgDialogTag.COPY_ADVERTISING_GROUP].includes(dialogTitle)">
                <PlusForm ref="formRef" v-model="form" :columns="formColumns" :rules="formRule"
                    :submit-loading="isPending" @submit="adGroupSubmit">
                    <template #footer="{ handleSubmit, handleReset }">
                        <div class="form-btn">
                            <el-button type="primary" :loading="isPending" @click="handleSubmit">
                                提交
                            </el-button>

                            <el-button plain @click="handleReset">
                                重置
                            </el-button>
                        </div>
                    </template>
                </PlusForm>
            </template>
            <!-- 商品配置 -->
            <template v-if="dialogTitle === adgDialogTag.ADVERTISING_CONFIG">
                <goods-config v-model="groupId" />
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
:deep(.el-tabs__nav-wrap::after) {
    height: 0;
}

:deep(.operate-btns .el-button) {
    margin: 0;
    padding: 6px;
}

.form-btn {
    display: flex;
    justify-content: flex-end;
    width: 100%;
}

.status {
    width: 52px;
    height: 24px;
    border-radius: 2px;
    line-height: 24px;
    text-align: center;
    font-size: 12px;
    margin: 0 auto;

    &.status-0 {
        background-color: #fff8f0;
        color: #e9810b;
    }

    &.status-1 {
        background-color: #f0fff0;
        color: #18b918;
    }

    &.status-2 {
        background-color: #f2f3f5;
        color: #86909c;
    }
}
</style>

<style lang="scss">
.ad-config-dialog {
    // height: 88% !important;

    .el-dialog__body {
        height: 80%;
        overflow-y: auto;
    }
}

.dialog-title {
    font-size: 18px;

    >.mark {
        font-size: 14px;
        color: #4e5969;
    }
}

.goods-group {
    .ad-by-stages {
        display: flex;
        flex-wrap: wrap;

        .time-item {
            display: flex;
            width: 310px;
            margin-bottom: 12px;

            .ad-time-piker {
                display: flex;
                align-items: center;
                position: relative;

                >.sort {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 30px;
                    height: 32px;
                    display: block;
                    font-size: 16px;
                    line-height: 32px;
                    border-right: 1px solid #e6ebf5;
                    text-align: center;
                    cursor: pointer;

                    &.active {
                        color: var(--el-color-primary);
                        border-right: 1px solid var(--el-color-primary);
                    }
                }

                &.active {
                    .el-range-editor.el-input__wrapper {
                        border: 1px solid var(--el-color-primary);
                    }
                }
            }

            .el-range-editor.el-input__wrapper {
                width: 260px;
                padding-left: 40px;
            }

            .icon-btns {
                display: flex;
                align-items: center;
                margin-left: 10px;

                .el-icon {
                    font-size: 18px;
                    cursor: pointer;

                    &.add {
                        color: var(--el-color-primary);
                        margin-right: 6px;
                    }

                    &.del {}
                }
            }
        }
    }
}
</style>
